#!/usr/bin/python
# coding:utf-8

from pyftpdlib.authorizers import DummyAuthorizer
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer
import threading
from time import sleep
import os
import jkzuc


class MyFtpHandle(FTPHandler):
    """
    回调,ftphandle特性

    """

    def on_file_received(self, file):
        program_path = jkzuc.jkroot_dir + "/scripts/program/"
        if program_path in file:
            dirname = os.path.dirname(os.path.abspath(file))
            os.utime(dirname, None)
        else:
            return


class FtpServer(threading.Thread):

    def __init__(self, threadname, port):
        threading.Thread.__init__(self, name=threadname)
        self.port = port
        self.serveripaddr = "0.0.0.0"

    def run(self):
        #  Instantiate a dummy authorizer for managing 'virtual' users
        authorizer = DummyAuthorizer()
        # 没有 scripts 或者 program 目录时，此处会抛出异常，导致 ftp 服务器无法正常运行
        os.system("mkdir -p " + os.path.join(jkzuc.jkroot_dir, "scripts", "program"))
        #  Define a new user having full r/w permissions and a read-onlyanonymous user
        authorizer.add_user("jaka", "jaka12345", jkzuc.jkroot_dir + "/scripts", perm="elradfmwM")
        authorizer.add_user("Prog", "ShanghaiJAKA", jkzuc.jkroot_dir + "/scripts/program", perm="elradfmwM")
        #  authorizer.add_anonymous(os.getcwd())
        #  Instantiate FTP handler class
        handler = MyFtpHandle
        handler.authorizer = authorizer
        #  Define a customized banner (string returned when client connects)
        handler.banner = "pyftpdlib based ftpd ready."

        #  Specify a masquerade address and the range of ports to use for
        #  passive connections.  Decomment in case you re behind a NAT.
        # handler.masquerade_address = '151.25.42.11'
        # handler.passive_ports = range(60000, 65535)

        #  Instantiate FTP server class and listen on 0.0.0.0:2121
        address = (self.serveripaddr, self.port)
        server = FTPServer(address, handler)
        #  set a limit for connections
        server.max_cons = 256
        # 单个IP 最大连接数（APP后续会开启多线程进行文件传输来进行优化，原先的5个连接可能不够用）
        server.max_cons_per_ip = 64
        # 15 秒无数据交互后，server会发送探寻帧若仍然没有应答则当作无效连接关闭。避免出现APP 打开连接后因异常情况未关闭，过多的连接未关闭导致无法建立新连接。
        server.timeout = 15
        #  start ftp server
        # TODO
        server.serve_forever(timeout=15)  # timeout属性必须设置，否则在修改系统时间后可能会造成栈溢出,但具体数值还有待商榷


def start():
    Thread_ftp_server = FtpServer("FtpServer", 2121)
    Thread_ftp_server.setDaemon(True)
    Thread_ftp_server.start()
    while True:
        sleep(24 * 60 * 60)


if __name__ == "__main__":
    start()
